package jp.co.isr.test.nkgm.pgf.ui.tab.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TabHost;
import android.widget.TabHost.TabContentFactory;

import jp.co.isr.test.nkgm.pgf.ui.tab.TabInitializer;

public class WebViewTabInitializer implements TabInitializer{
	
	private Context context;
	public WebViewTabInitializer(){}
	
	@Override
	public void initialize(TabHost tabHost) {
		context = tabHost.getContext();
		for(WebViewTabPage page : geTabPages()){
			tabHost.addTab(tabHost.newTabSpec(page.tag)
					.setIndicator(page.indicator)
					.setContent(new WebViewTabContentFactory(context, page.loadUrl)));
		}
	}
	
	private List<WebViewTabPage> geTabPages(){
		Properties viewConfig = new Properties();
		try {
			viewConfig.load(context.getAssets().open("webviewtab_config.properties"));
			int pageCount = Integer.parseInt((String)viewConfig.get("tab.page.count"));
			List<WebViewTabPage> list = new ArrayList<WebViewTabPage>();
			for(int page = 1; page <= pageCount; page++){
				
				list.add(new WebViewTabPage(
						viewConfig.getProperty("tab.page.page" + page + ".tag"),
						viewConfig.getProperty("tab.page.page" + page + ".indicator"),
						viewConfig.getProperty("tab.page.page" + page + ".url")));
			}
			
			return list;
			
		} catch (IOException e) {
			return Collections.emptyList();
		}
		
	}
	
	private class WebViewTabPage {
		private String tag;
		private String indicator;
		private String loadUrl;
		private WebViewTabPage(String tag, String indicator, String loadUrl){
			this.tag = tag;
			this.indicator = indicator;
			this.loadUrl = loadUrl;
		}
	}
	
	private class WebViewTabContentFactory implements TabContentFactory{

		private String loadUrl;
		private Context context;
		private WebViewTabContentFactory(Context context, String url){
			this.loadUrl = url;
			this.context = context;
		}
		
		@SuppressLint("SetJavaScriptEnabled")
		@Override
		public View createTabContent(String tag) {
			WebView webview = new WebView(context);
			webview.setWebViewClient(new WebViewClient());
			WebSettings settings = webview.getSettings();
			settings.setDomStorageEnabled(true);
			settings.setJavaScriptEnabled(true);
			webview.loadUrl(loadUrl);
			return webview;
		}
		
	}
	
}
